
package la.foton.atividade.dao;

import java.io.PrintWriter;
import java.io.StringWriter;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;

/**
 * Exception interceptor (AOP)
 */
@ManagedBean(name = "exceptionInterceptor")
public class ExceptionInterceptor implements MethodInterceptor
{

   private static final Logger logger = LoggerFactory.getLogger(ExceptionInterceptor.class);

   final FacesContext facesContext = FacesContext.getCurrentInstance();

   @Autowired
   MailSender mailSender;

   public ExceptionInterceptor()
   {
      super();
   }

   public Object invoke(MethodInvocation method) throws Throwable
   {
      Object result = null;
      try
      {
         result = method.proceed();
      }
      catch (Exception e)
      {
         // Building stack trace string
         StringWriter stackTrace = new StringWriter();
         e.printStackTrace(new PrintWriter(stackTrace));
         // Building e-mail
         SimpleMailMessage email = new SimpleMailMessage();
         email.setFrom("gleyson.santos@foton.la");

         email.setTo("gleyson.santos@foton.la");
         email.setSubject("[MyApp] Exception in '" + method.getMethod().getName() + "' method");
         email.setText(
                  "Exception in: " + method.getMethod().getName() + "\n\n" +
                     "Class: " + method.getMethod().getDeclaringClass().getName() + "\n\n" +
                     "Message: " + e.getMessage() + "\n\n" +
                     "StackTrace:\n" + stackTrace.getBuffer().toString()
                  );
         // Sending e-mail
         addErrorMessage(null, "teste");
         try
         {
            this.mailSender.send(email);
         }
         catch (MailException mailException)
         {
            logger.error(mailException.getMessage());
         }
         // throw e;

      }
      return result;
   }

   protected void addErrorMessage(String componentId, String errorMessage)
   {
      addMessage(componentId, errorMessage, FacesMessage.SEVERITY_ERROR);
   }

   /**
    * Metodo comum
    * 
    * @param componentId
    * @param errorMessage
    * @param severity
    */
   private void addMessage(String componentId, String errorMessage,
      Severity severity)
   {
      FacesMessage message = new FacesMessage(errorMessage);
      message.setSeverity(severity);
      FacesContext.getCurrentInstance().addMessage(componentId, message);
   }

}
